import React, { Component } from 'react';
import { marked } from 'marked';
import hljs from 'highlight.js';
import { Button } from 'antd';
import { Input } from 'antd';
import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons';
import { CSSTransition } from 'react-transition-group';
import './style.less';

const { TextArea } = Input;

export interface MarkdownState {
  content: string;
  isShowDisplay: boolean;
}
export interface MarkdownProps {
  content: string;
  onChange: Function;
}

class Markdown extends Component<MarkdownProps, MarkdownState> {
  private editor!: React.RefObject<HTMLTextAreaElement>;
  private display!: React.RefObject<HTMLDivElement>;
  constructor(props: MarkdownProps) {
    super(props);
    this.state = {
      content: '',
      isShowDisplay: true,
    };
    this.editor = React.createRef();
    this.display = React.createRef();
    this.init();
  }

  init() {
    if (!this.props.content) return;
    this.setState({
      content: this.props.content,
    });
  }

  editorChange(e: InputEvent) {
    if (this.display.current) {
      marked.setOptions({
        renderer: new marked.Renderer(),
        highlight: function (code, lang) {
          const language = hljs.getLanguage(lang) ? lang : 'plaintext';
          return hljs.highlight(code, { language }).value;
        },
        langPrefix: 'hljs language-', // highlight.js css expects a top-level 'hljs' class.
        pedantic: false,
        gfm: true,
        breaks: false,
        sanitize: false,
        smartLists: true,
        smartypants: false,
        xhtml: false,
      });
      this.display.current.innerHTML = marked(e.target?.value);
      console.log(this.props);

      this.props.onChange({
        content: e.target?.value,
        htmlContent: this.display.current.innerHTML,
      });
    }
  }

  switchDisplay() {
    this.setState({
      isShowDisplay: !this.state.isShowDisplay,
    });
  }

  render() {
    return (
      <div id="markdown" className="markdown">
        <TextArea
          onChange={this.editorChange.bind(this)}
          ref={this.editor}
        ></TextArea>
        <Button
          size="middle"
          onClick={this.switchDisplay.bind(this)}
          icon={
            !this.state.isShowDisplay ? (
              <CaretLeftOutlined />
            ) : (
              <CaretRightOutlined />
            )
          }
        ></Button>
        <CSSTransition
          unmountOnExit
          classNames="fade"
          in={this.state.isShowDisplay}
          timeout={500}
        >
          <section ref={this.display} className="show"></section>
        </CSSTransition>
      </div>
    );
  }
}
export default Markdown;

